import { Component } from 'react';
import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import Styles from './index.module.scss';
import logoSrc from 'assets/logo.png';
import { loginApi } from '../../api/user';
import { setToken } from '../../utils/storage';

export default class Login extends Component {
  // 提交表单且数据验证成功后回调事件
  handleSubmit = async (values) => {
    try {
      const res = await loginApi(values);
      // 本地存储
      // localStorage.setItem('geek-pc', res.data.token);
      setToken(res.data.token);
      // 跳转页面
      this.props.history.push('/');
      // 提示用户
      message.success('登录成功');
    } catch (error) {
      // console.dir(error);
      // 错误提示
      message.warning(error.response.data.message);
    }
  };
  render() {
    return (
      <div className={Styles.login}>
        <Card className="login-container">
          {/* 图片 */}
          <img src={logoSrc} alt="" className="login-logo" />
          {/* 表单 */}
          <Form
            autoComplete="off"
            onFinish={this.handleSubmit}
            initialValues={{
              mobile: '13811111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '手机号不能为空!',
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入11位手机号码',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空!',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '6位数字验证码',
                },
                {},
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) => {
                    // console.log('value  ---  ', value);
                    if (value) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject('请阅读并勾选');
                    }
                    // console.log('value  ---  ', value);
                    // return Promise.reject(value);
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
